package com.qen.sheji.zhuanshiqi;

import java.io.*;

public class FileReaderWriter implements ReaderWriter {

    private String filePath;

    public FileReaderWriter(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public String read() {
        var sb = new StringBuilder();
        var file = new File(filePath);
        var br = (BufferedReader) null;
        var fr = (FileReader) null;
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            var s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return sb.toString();
    }

    @Override
    public void write(String content) {
        var file = new File(filePath);
        var fileWriter = (FileWriter)null;
        var bw = (BufferedWriter)null;
        try {
            fileWriter = new FileWriter(file);
            bw = new BufferedWriter(fileWriter);
            bw.write(content);
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                bw.close();
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
